<template>
  <div class="user-profile-container">
    <div class="background-image"></div>
    <div class="profile-box">
      <h2 class="section-title">修改用户资料</h2>
      <div class="profile-form">
      <div class="form-grid">
        <!-- 用户头像 -->
        <div class="avatar-section">
          <div class="avatar-preview">
            <img 
              :src="avatarPreview || '/src/images/default-avatar.jpg'"
              alt="用户头像"
              class="avatar-image">
          </div>
          <input 
            type="file"
            ref="avatarInput"
            @change="handleAvatarUpload"
            accept="image/*"
            class="avatar-upload">
        </div>
        
        <!-- 用户名 -->
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text"
            id="username"
            v-model="userData.userName"
            placeholder="请输入用户名">
        </div>
        
        <!-- 密码 -->
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password"
            id="password"
            v-model="userData.password"
            placeholder="请输入新密码">
        </div>
        
        <!-- 电话 -->
        <div class="form-group">
          <label for="phone">电话</label>
          <input 
            type="tel"
            id="phone"
            v-model="userData.phone"
            placeholder="请输入电话号码">
        </div>
        
        <!-- 邮箱 -->
        <div class="form-group">
          <label for="email">邮箱</label>
          <input 
            type="email"
            id="email"
            v-model="userData.email"
            placeholder="请输入邮箱地址">
        </div>
      </div>
      
      <button @click="submitProfile" class="submit-btn">保存修改</button>
    </div>
        </div>
    </div>
 
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import api from '@/api/index';

const router = useRouter();
const avatarInput = ref(null);

const userData = ref({
  userName: '',
  password: '',
  phone: '',
  email: ''
});

const avatarPreview = ref('');

// 在组件挂载时从localStorage获取用户信息
onMounted(() => {
  try {
    const userInfoStr = localStorage.getItem('userInfo');
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      // 设置用户数据
      userData.value = {
        ...userData.value,
        userName: userInfo.userName || '',
        phone: userInfo.phone || '',
        email: userInfo.email || ''
      };
      // 设置头像预览
      avatarPreview.value = userInfo.avatarUrl || '';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
});

const handleAvatarUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  const reader = new FileReader();
  reader.onload = (e) => {
    avatarPreview.value = e.target.result;
  };
  reader.readAsDataURL(file);
};

// 将base64转换为Blob
const dataURItoBlob = (dataURI) => {
  const byteString = atob(dataURI.split(',')[1]);
  const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
};

const submitProfile = async () => {
  try {
    // 获取用户ID
    const userInfoStr = localStorage.getItem('userInfo');
    if (!userInfoStr) {
      alert('未找到用户信息，请重新登录');
      router.push('/login');
      return;
    }
    
    const userInfo = JSON.parse(userInfoStr);
    // 确保userId是字符串类型
    const userId = String(userInfo.userId);
    
    // 准备用户数据
    const userDTO = {
      userName: userData.value.userName,
      phone: userData.value.phone,
      email: userData.value.email
    };
    
    // 如果填写了密码，则添加到userDTO
    if (userData.value.password) {
      userDTO.password = userData.value.password;
    }
    
    // 获取头像文件（如果有上传）
    let avatarFile = null;
    if (avatarInput.value && avatarInput.value.files && avatarInput.value.files[0]) {
      avatarFile = avatarInput.value.files[0];
    }
    
    // 调用接口更新用户信息
    const response = await api.updateUserById(userId, userDTO, avatarFile);
    
    if (response.data.flag==true) {
      // 更新成功，更新localStorage中的用户信息
      const updatedUserInfo = {
        ...userInfo,
        ...userDTO,
        avatarUrl: response.data.result.avatarUrl || userInfo.avatarUrl
      };
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
      
      alert('资料修改成功！');
      router.push('/user/info');
    } else {
      console.error('更新用户信息失败:', response.data);
      alert('资料修改失败：' + response.data);
    }
  } catch (error) {
    console.error('提交用户资料失败:', error);
    alert('提交失败，请稍后重试');
  }
};
</script>

<style scoped>
.user-profile-container {
  position: relative;
  height: 100vh;
  max-width: 100vw;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('/src/images/demo.jpg');
  background-size: cover;
  background-position: center;
  z-index: -1;
}

.profile-box {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  max-width: 500px;
  width: 100%;
  background: rgba(20, 20, 20, 0.8);
  padding: 2.5rem;
  border-radius: 8px;
}

.section-title {
  font-size: 2rem;
  margin-bottom: 2rem;
  text-align: center;
  color: #c0c0c0;
  font-weight: 250;
  letter-spacing: 0.05em;
}

.profile-form {
  padding: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.avatar-section {
  grid-column: span 2;
  text-align: center;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  margin: 0 auto 15px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #ddd;
  position: relative;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-group {
  margin-bottom: 2.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #c0c0c0;
  font-size: 1.1rem;
}

input {
  width: 90%;
  padding: 1rem;
  background: rgba(20, 20, 20, 0.8);
  border: 1px solid #333;
  border-radius: 4px;
  color: #fff;
  font-size: 1.1rem;
}

.submit-btn {
  width: 100%;
  padding: 1rem;
  background: #ffffff;
  color: #000000;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1.1rem;
  transition: background 0.3s;
  margin-top: 1rem;
}

.submit-btn:hover {
  background: #e0e0e0;
}

.avatar-upload {
  width: 50%;
  height: 30px;
  
  display: block;
  
  position: relative;
  cursor: pointer;

}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
}
</style>